package prueba.prueba;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import prueba.prueba.helpers.WordIso;
import prueba.prueba.helpers.WordsISOHelper;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class PruebaActivity extends Activity{

	public static int num_practices = 20;
	private int index = 0; //
	private LinkedList<String> key = new LinkedList<String>();
	private LinkedList<String> meaning = new LinkedList<String>();
	private LinkedList<String> md5 = new LinkedList<String>();
	private int hits = 0;
	private boolean started = false;
	private LinkedList<WordIso> list_words;
	
	private CheckBox option = null;
	//Button btn = null;
	private EditText text  = null;
	private TextView texto = null;
	private Spinner tipo = null;
	private Spinner languages = null;
	private WordsISOHelper helper;
	private int type_practice;
	private String iso_language;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		helper = new WordsISOHelper(this, "Words6", null,7);
		texto =(TextView)findViewById(R.id.textView1);
		
		option = (CheckBox)findViewById(R.id.checkBox1);
		option.setText("Preguntar inversa");
		text =(EditText)findViewById(R.id.editText1);
		tipo =(Spinner)findViewById(R.id.spinner1);
		languages =(Spinner)findViewById(R.id.spinner2);
		
		ArrayAdapter adapter = ArrayAdapter.createFromResource(this,R.array.tipos_word,android.R.layout.simple_spinner_item);
		//Añadimos el layout para el menú
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		//Le indicamos al spinner el adaptador a usar
		tipo.setAdapter(adapter);
		
		ArrayAdapter languages_adapter = ArrayAdapter.createFromResource(this,R.array.languages,android.R.layout.simple_spinner_item);
		languages_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		//Le indicamos al spinner el adaptador a usar
		
		try{
			languages.setAdapter(languages_adapter);
			
		}
		catch(Exception ex){
			Log.e("","revienta al poner al spinner");
		}
		
	//	EditText edittext =(EditText)findViewById(R.id.editText1);
		text.setOnKeyListener(new OnKeyListener() {
		    public boolean onKey(View v, int keyCode, KeyEvent event) {
		        // If the event is a key-down event on the "enter" button
		        if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
		            (keyCode == KeyEvent.KEYCODE_ENTER)) {
		        	action();
		          // Perform action on key press
		         // Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();
		          return true;
		        }
		        return false;
		    }
		});
		
		/************
		 * Configuracion de los botones.
		 */
		
		text.setText("");
		
		
		Button btn3=(Button)findViewById(R.id.button3);
		btn3.setOnClickListener(new Button.OnClickListener() {
		    public void onClick(View v) {

		    	String texto = addUmbrella(text.getText().toString());
		    	
		    	if (texto != null){
		    		text.setText(texto);
		    		text.setSelection(text.getText().length());
		    	}
		    }
		});
		btn3.setText("umbrella");
			
	}
	
	private boolean init2(){
		
	
		tipo.setEnabled(false);	
		String item = (String)tipo.getSelectedItem().toString();
		String language = (String)languages.getSelectedItem().toString();
		
		Log.i("prueba","Este es el item " + item);
		//	Toast.makeText(PruebaActivity.this,item,Toast.LENGTH_SHORT).show();
		
		int type = TypeWords.valueOf(item.toLowerCase()).ordinal();
		int id_language = Languages.valueOf(language).ordinal();
			
		iso_language = LanguagesIso.values()[id_language].name();
		
		// esto se puede reutilizar.
		
		type_practice = option.isChecked()?1:0;
		
		try {
			
			list_words = helper.select_words(type,iso_language,type_practice);
			
			//Collections.sort(list_words);
			
			
			for(int i = 0; i < list_words.size();i++){
				key.add(list_words.get(i).getWord());
				meaning.add(list_words.get(i).getMeaning(iso_language));
				md5.add(list_words.get(i).getMd5());
			}
			
			if(key.size() == 0 || meaning.size() == 0)
				return false;
			
		}
		catch (Exception e) {
			Toast.makeText(PruebaActivity.this,"Peta",Toast.LENGTH_SHORT).show();
			String error = e.getMessage() + e.getCause();
			Log.i("",error);
			
		}	
		return true;
	}
	
	//select_words
	
	private void action(){
	
		if (!started){
			started =true;
			if (!init2()){
				Toast.makeText(PruebaActivity.this,"Peta",Toast.LENGTH_SHORT).show();
				System.exit(0);
			}
				
				
			//btn.setText("Siguiente");
			option.setEnabled(false);
			//meaning
			
			if (option.isChecked()){
				LinkedList<String> aux = key;
				key = meaning;
				meaning = aux;
			}
		}
		
	
		option.setEnabled(false);

			if (index < key.size()){
				if (index != 0){
					String result = text.getText().toString().equalsIgnoreCase(meaning.get(index - 1))?"Acertaste":"Fallaste era " + meaning.get(index - 1);
					int id = list_words.get(index).getId();
					int num_hits =  0;//list_words.get(index).getNumHits();
					int num_practices =  0;//list_words.get(index).getNumPractices();
					
					
					
					String mymd5 = md5.get(index-1);
					if (text.getText().toString().equalsIgnoreCase(meaning.get(index - 1))){
							hits++;
							num_hits++;
					}
					num_practices++;
					// En cualquier caso indicamos que la ha practicado.
					//helper.update(id, num_hits, num_practices);
					
					// Te falta por cambiar esto.
					
					helper.setPractice(mymd5,iso_language,num_practices,num_hits,type_practice);
					
					text.setText("");
					Toast.makeText(PruebaActivity.this,result,Toast.LENGTH_SHORT).show();
				}
				
				
				texto.setText(key.get(index));
				index++;
			}
			else { // De esta no se esta guardando la practica.
				
				/**
				 * Guarreria.
				 * 
				 */
				
				//String result = text.getText().toString().equalsIgnoreCase(meaning.get(index - 1))?"Acertaste":"Fallaste";
				//text.setText("");
				if (text.getText().toString().equalsIgnoreCase(meaning.get(index - 1)))
						hits++;
				
				text.setText("");
			//	Toast.makeText(PruebaActivity.this,result,Toast.LENGTH_SHORT).show();
		
				// refactor.
				
				String result = hits + "/" + meaning.size() + "Aciertos";
		
				new AlertDialog.Builder(PruebaActivity.this)
				.setTitle("Aciertos")
				.setMessage(result)
				.setNeutralButton("Ok",
				new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog,int which) {
					System.exit(0);
				}

				}).show();
			}
		text.setText("");
	}
	
	private String addUmbrella(String text){
		
		String letter = "";
		
		if (text.length() == 0)
			return null;
		if (text.length() == 1)
			letter = text;
		else letter = text.substring(text.length() - 1 ,text.length());	
		
		if (letter.equalsIgnoreCase("a"))
			letter = "â";
		else if (letter.equalsIgnoreCase("e"))
			letter = "ê";
		else if (letter.equalsIgnoreCase("i"))
			letter = "î";
		else if (letter.equalsIgnoreCase("o"))
			letter = "ô";
		else if (letter.equalsIgnoreCase("u"))
			letter = "û";
		else return null;
		
		if (text.length() == 1)
			return letter;
		else return text.substring(0,text.length() - 1) + letter;
	}
	

	public String getData(String url) {

		HttpClient httpclient = new DefaultHttpClient();
	    HttpPost httppost = new HttpPost(url);

	    try {
	        // Add your data
	        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
	        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
	        nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

	        // Execute HTTP Post Request
	        HttpResponse response = httpclient.execute(httppost);
	        
	        StringBuilder texto = inputStreamToString(response.getEntity().getContent());
	        return texto.toString();
	        
	        
	    
	    } catch (ClientProtocolException e) {
	    	 return "Revienta en client protocol.";
	    } catch (IOException e) {
	    	 return "Revienta en IO exception.";
	    }
	}
	
	// Fast Implementation
	private StringBuilder inputStreamToString(InputStream is) {
		
		try{
				
		    String line = "";
		    StringBuilder total = new StringBuilder();
		    
		    // Wrap a BufferedReader around the InputStream
		    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
	
		    // Read response until the end
		    while ((line = rd.readLine()) != null) { 
		        total.append(line); 
		    }
		    
		    // Return full string
		    return total;
	    
		}
		catch(Exception ex){
			return null;
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    //Alternativa 1
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu, menu);
	    return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case R.id.MnuOpc1:
	        	request_url_sync();
	            return true;
	        case R.id.MnuOpc2:
	        	// Estaria bien preguntar si quieres salir.
	        	System.exit(0);
	            return true;
	        case R.id.MnuOpc3:
	        	action();
	            return true;
	            
	        case R.id.MnuOpc4:
	       	
	        	new AlertDialog.Builder(this)
	        	.setTitle("Borrar historial")
	        	.setMessage("¿Estas seguro, se borraran todas las prácticas")
	        	.setIcon(android.R.drawable.ic_dialog_alert)
	        	.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

	        	    public void onClick(DialogInterface dialog, int whichButton) {
	        	    	helper.clearHistory();
	        	    }})
	        	 .setNegativeButton(android.R.string.no, null).show();
	        	
	        	return true;
	            
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	private void process_JSON(String text){
		
		try {
			helper.deleteAll();
			JSONObject response = new JSONObject(text);
			String ts = response.getString("ts");
			JSONArray jsonArray = response.getJSONArray("words");
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject word = jsonArray.getJSONObject(i);
				
				int id = word.getInt("id");
				
				String es = word.getString("es");
				String en = word.getString("en");
				String fr = word.getString("fr"); // falta meter mas strings.
				
				
				String de = word.getString("es");
				String ar = word.getString("ar");
				String ch = word.getString("ch"); // falta meter mas strings.
				
				String ru = word.getString("ru");
				String jp = word.getString("jp"); // falta meter mas strings.
				
				
				
				String md5 = word.getString("md5");
				
				int type_word = 0;
				try{
					type_word = TypeWords.valueOf(word.getString("type")).ordinal();
					
				//	if (type_word != 0)
					//	Toast.makeText(PruebaActivity.this,"Pone uno que no es sustantivo",Toast.LENGTH_SHORT).show();
					
				}
				catch(Exception ex){
					Log.e("Activity","revienta al coger el tipo de palabra");
				}
				
				// Para asegurarse lo mejor es borrar la palabra y volverla a meter.
			
				//helper.delete(id); // Tambien se podria borrar por md5 o borrar toda la tabla, es otra opcion.
				helper.create(id, type_word,es,en,fr,de,ru,ch,ar,jp,md5);
				
			}
		} catch (Exception e) {
			
			String log = e.getMessage() + e.getCause();
			Log.i("",log);
		}
		
		Toast.makeText(PruebaActivity.this,"Sincronización finalizada",Toast.LENGTH_SHORT).show();
		
	}
	
	
	private void request_url_sync(){
		
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle("Direccion");
		alert.setMessage("Introduce la dirección para sincronizar");

		// Set an EditText view to get user input 
		final EditText input = new EditText(this);
		input.setText("http://192.168.1.10/get_data_iso2.php");
		alert.setView(input);

		alert.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int whichButton) {
		  String value = input.getText().toString();
		  // Do something with value!
		  // TODO:Comprobar que es una URL.
		  	ProgressDialog waiting = ProgressDialog.show(PruebaActivity.this, "", "Loading. Please wait...", true);
		  
		  	waiting.show();
		  
		  	String data =  getData(value);
			Toast.makeText(PruebaActivity.this,"estos son los datos "+data,Toast.LENGTH_SHORT).show();
			process_JSON(data);
			
			waiting.hide();
			
		}
		});

		alert.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
		  public void onClick(DialogInterface dialog, int whichButton) {
		    // Canceled.
		  }
		});

		alert.show();
	}
	
	
	
}